<?php

namespace app\api\controller;

use addons\alisms\controller\Index as smsIndex;
use addons\ttlock\ttlock;
use app\admin\model\Category;
use app\admin\model\Fangjian;
use app\admin\model\Gonggao;
use app\admin\model\Jiameng;
use app\admin\model\Order;
use app\admin\model\Pinglun;
use app\admin\model\Renzheng;
use app\common\controller\Api;
use app\common\service\Wechat;
use GuzzleHttp\Client;
use think\Config;
use think\Db;
use think\db\exception\DbException;
use think\Env;
use think\Session;
use app\admin\model\UserCategoryRmb;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function test()
    {
        $kaimen = Config::get('site.status');
        print_r($kaimen);
        die;
    }

    /**
     * 小程序登录
     *
     * @param string $code code
     * @param string $nickName nickName
     */
    public function loginInfo(Wechat $wechat)
    {
        //        接收前台传来的值
        $code = input('code');
        $nickName = input('nickName');
        $iv = input('iv');
        $encryptedData = input('encryptedData');
        $avatar = input('avatar');
        //        判断是否为空
        if (empty($code) || empty($nickName)) {
            return json(['code' => 0, 'data' => '', 'mag' => '参数不正确']);
        }

        $res = $wechat->login($code);
        dump($res);
        die;

        //        print_r($res);die;
        //        调用成功后定义一个新的数组，最主要的session_key和openid两个值
        $arr = [
            'username' => $nickName,
            'nickname' => $nickName,
            //            'log'=>$log,
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'code' => $code,
            "avatar" => $avatar,
        ];

        //        new一个模型
        $model = new User();
        //        根据openid查询一条数据，重点！！！！tp用find，laravel用first
        $data = $model->where('openid', $res['openid'])->find();
        //        如果有就修改session_key这个字段，如果没有就新添加一条数据
        if (!empty($data)) {
            $data = $model->where('openid', $res['openid'])->update([
                'session_key' => $res['session_key'],
                "username" => $nickName,
                "nickname" => $nickName,
                "avatar" => $avatar,
            ]);
            $data = $model->where('openid', $res['openid'])->find();

        } else {
            $data = $model->save($arr);

            $data = $model->where('id', $data->id)->find();
        }
        //        返回主键ID

        Session::set("user", $data);


        $this->success('请求成功', $data);
        //        return json(['code'=>200,'id'=>$item['id'],'msg'=>'登录成功']);
    }

    /**
     * 利用腾讯地图api
     * 计算两点地理坐标之间的距离
     */
    function getDistance($from, $to)
    {
        $key = 'EGRBZ-7OQ33-GVD3M-3MXOQ-VJYB3-5RBHN'; //腾讯地图开发自己申请
        $mode = 'driving'; //driving（驾车）、walking（步行）
        //        $from = '填写你的起点坐标'; //例如：39.14122,117.14428
        //        $to = '起点坐标;终点坐标'; //例如(格式：终点坐标;起点坐标)：39.10149,117.10199;39.14122,117.14428
        $url = 'https://apis.map.qq.com/ws/distance/v1/?mode=' . $mode . '&from=' . $from . '&to=' . $to . '&key=' . $key;
        $info = file_get_contents($url);
        $info = json_decode($info, true);
        return isset($info['result']) ? round($info['result']['elements']['0']['distance'] / 1000, 1) : 0;
    }


    public function getJuli($lng1 = 0, $lat1 = 0, $lng2 = 0, $lat2 = 0)
    {

        //        print_r($lng1);die;

        $lng1 = 116.32599;  //经度1
        $lat1 = 39.88814;   //纬度1

        $lng2 = 116.45627;  //经度2
        $lat2 = 39.91999;   //纬度2
        if (empty($lng1)) {
            return 0;
        }
        if (empty($lat1)) {
            return 0;
        }
        if (empty($lng2)) {
            return 0;
        }
        if (empty($lat2)) {
            return 0;
        }

        $EARTH_RADIUS = 6378137;   //地球半径
        $RAD = pi() / 180.0;
        $radLat1 = $lat1 * $RAD;
        $radLat2 = $lat2 * $RAD;
        $a = $radLat1 - $radLat2;    // 两点纬度差
        $b = ($lng1 - $lng2) * $RAD;  // 两点经度差
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $EARTH_RADIUS;
        $s = round($s * 10000) / 10000;

        $s = round($s);


        return $s;
        print_r($s);
        die;  //两个经纬度之间的距离

    }

    /**
     * 门店列表
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @ApiReturnParams   (name="name", type="string", required=true, sample="店铺名称")
     * @ApiReturnParams   (name="image", type="string", required=true, sample="店铺首页图片")
     * @param string $page 页
     * @param string $limit 条数
     * @param string $name 搜索名称
     * @param string $lng2 经度
     * @param string $lat2 纬度
     */
    public function mendian()
    {

        $page = input('page', 1);
        $limit = input('limit', 10);
        $name = input('name');
        $lng2 = input('lng2');
        $lat2 = input('lat2');

        if (!empty($name)) {
            $list = Category::where(['status' => 'normal', 'name' => ['like', '%' . $name . '%']])->order('weigh desc, id desc')->paginate($limit, false, [
                'page' => $page,
            ]);

        } else {
            $where['status'] = 'normal';

            $list = Category::where($where)->order('weigh desc, id desc')->paginate($limit, false, [
                'page' => $page,
            ]);
        }

        if (empty($list)) {
            $this->success('查询成功');
        }

        $list = $list->toArray();
        foreach ($list['data'] as &$v) {
            //获取距离

            //            $v['juli'] = $this->getJuli($v['lng'],$v['lat'],$lng2,$lat2);
            $from = $v['lat'] . ',' . $v['lng'];
            $to = $lat2 . ',' . $lng2;

            $v['juli'] = $this->getDistance($from, $to);

//            $v['image'] = 'http://' . $_SERVER['HTTP_HOST'] . $v['image'];
            $v['image'] = cdnurl($v['image'], true);

            $v['images'] = explode(',', $v['images']);
            foreach ($v['images'] as &$vo) {
//                $vo = 'http://' . $_SERVER['HTTP_HOST'] . $vo;
                $vo = cdnurl($vo, true);
            }

        }
        $kaimen = Config::get('site.status');
        $list['kaimen_status'] = $kaimen;
        $sousuo = Config::get('site.sousuo');
        $list['sousuo'] = $sousuo;
        $chakan = Config::get('site.chakan');
        $list['chakan'] = $chakan;
        $shouqi = Config::get('site.shouqi');
        $list['shouqi'] = $shouqi;
        $name = Config::get('site.name');
        $list['name'] = $name;
        $this->success('查询成功', $list);
    }

    /**
     * 门店详情
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $dp_id 店铺id
     * @param string $page 页
     * @param string $limit 条数
     * @ApiReturnParams   (name="name", type="string", required=true, sample="店铺名称")
     * @ApiReturnParams   (name="image", type="string", required=true, sample="店铺首页图片")
     */
    public function mendianDetai()
    {
        $dp_id = input('dp_id');
        $user_id = input('user_id');
        $page = input('page', 1);
        $limit = input('limit', 10);

        $data = Category::where('id', $dp_id)->find();
        //        print_r($data);die;
        if (empty($data)) {
            $this->success('店铺不存在');
        }
        $data = $data->toArray();

        $fangjian = Fangjian::where('category_id', $data['id'])->order('id desc')->paginate($limit, false, [
            'page' => $page,
        ]);
        foreach ($fangjian as &$item) {
            $isOrder = Db::name('order')->where([
                'fangjian_id' => $item['id'],
                'status' => 2,
            ])->field("fuwu,fuwu_sc")->find();
            $item['is_tip'] = 0;
            if ($isOrder) {
                $q_time = strtotime($isOrder['fuwu']);
                $f_time = $q_time + $isOrder['fuwu_sc'] * 60 * 60;
                $item['is_tip'] = 1;
                $item['tip_msg'] = "使用中" . date("H:i", $f_time) . "结束";
            } elseif ($item['is_dasao'] == 1) {
                $item['is_tip'] = 2;
                $item['tip_msg'] = "保洁中";
            }

            $item['is_order'] = 1;
            if ($item['is_dasao'] == 1 && Config::get('site.dasao_order') == 1) {
                $item['is_order'] = 0;
            }


            $item['no_free_time'] = look_time($item['id'], $item['duration'], true);
            $item['package'] = Db::name('fangjian_package')->field("times,price")->where(['fj_id' => $item['id']])->limit(2)->select();
        }

        $data['fangjian'] = $fangjian;
        $data['pinglun'] = Pinglun::where('category_id', $data['id'])->order('id desc')->limit(5)->select();
        $data['pinglunCount'] = Pinglun::where('category_id', $data['id'])->order('id desc')->count();
        if (!empty($data['pinglun'])) {
            foreach ($data['pinglun'] as &$v) {
                $v['user'] = \app\admin\model\User::field('nickname,avatar')->where('id', $v['user_id'])->find();
                $v['createtime'] = date('Y/m/d', $v['createtime']);
                $v['images'] = array_filter(explode(',', $v['images']));
            }
        }
        $discount = UserCategoryRmb::getMemberLevel($user_id, $dp_id);
        foreach ($data['fangjian'] as &$v) {
            $v['image'] = cdnurl($v['image'], true);
            $v['org_price'] = $v['price'];
            if ($user_id) {
                $v['price'] = sprintf("%.2f", $v['price'] * $discount);
            }
        }
        //   $data['image'] = 'http://' . $_SERVER['HTTP_HOST'] . $data['image'];
        $data['image'] = cdnurl($data['image'], true);
        $data['images'] = explode(',', $data['images']);

        foreach ($data['images'] as &$v) {
            $v = cdnurl($v, true);
        }
        $this->success('查询成功', $data);
    }


    /**
     * 评论列表
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $dp_id 店铺id
     * @param string $page 页
     * @param string $limit 条数
     * @ApiReturnParams   (name="name", type="string", required=true, sample="店铺名称")
     * @ApiReturnParams   (name="image", type="string", required=true, sample="店铺首页图片")
     */
    public function punlun()
    {
        $dp_id = input('dp_id');
        $page = input('page', 1);
        $limit = input('limit', 10);

        $data = Category::where('id', $dp_id)->find();

        if (empty($data)) {
            $this->success('店铺不存在');
        }

        $list = Pinglun::where('category_id', $data['id'])->order('id desc')->paginate($limit, false, [
            'page' => $page,
        ]);
        if (empty($list['data'])) {
            $list = $list->toArray();
            foreach ($list['data'] as &$v) {
                $v['user'] = \app\admin\model\User::field('nickname,avatar')->where('id', $v['user_id'])->find();
                $v['createtime'] = date('Y/m/d', $v['createtime']);

                $v['images'] = explode(',', $v['images']);

            }

        }

        $this->success('查询成功', $list);
    }


    /**
     * 房间详情
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $fangjian_id 房间id
     */
    public function fjdetai()
    {
        $fangjian_id = input('fangjian_id');
        $user_id = input('user_id');
        $is_predetermine_time = input('is_predetermine_time', true);
        $data = Fangjian::where('id', $fangjian_id)->find();
        if (empty($data)) {
            $this->success('房间不存在');
        }
        $data = $data->toArray();
        $data['is_order'] = 1;
        if ($data['is_dasao'] == 1 && Config::get('site.dasao_order') == 1) {
            $data['is_order'] = 0;
        }


        $data['phone'] = Category::where('id', $data['category_id'])->value('phone');
        $data['dizhi'] = Category::where('id', $data['category_id'])->value('dizhi');
        $data['lng'] = Category::where('id', $data['category_id'])->value('lng');
        $data['lat'] = Category::where('id', $data['category_id'])->value('lat');
        $data['image'] = cdnurl($data['image'], true);
        $data['images'] = explode(',', $data['images']);
        $data['time'] = date('Y/m/d H:i:s', time());
        foreach ($data['images'] as &$v) {
            $v = cdnurl($v, true);

        }
        $data['org_price'] = $data['price'];
        $discount = UserCategoryRmb::getMemberLevel($user_id, $data['category_id']);
        $data['price'] = sprintf("%.2f", $data['price'] * $discount);

        $duration = $data['duration'];
        $data['no_free_time'] = look_time($fangjian_id, $duration, $is_predetermine_time);
        $data['duration'] = $duration; // 1 就是30分钟隔断  0就是15分钟隔断
        $data['booking_time'] = $data['booking_time']; // 起订时长
        $data['business_stare_time'] = Category::where('id', $data['category_id'])->value('business_stare_time'); // 开始营业时间
        $data['business_end_time'] = Category::where('id', $data['category_id'])->value('business_end_time'); // 开始营业时间
        $data['taocan'] = Config::get('site.taocan');
        $package_vip_price = $data['package_vip_price'];
        $data['package'] = Db::name('fangjian_package')->where(['fj_id' => $fangjian_id])->select();
        foreach ($data['package'] as &$package) {
            $package['org_price'] = $package['price'];
            if ($package_vip_price == 1) {
                $package['price'] = sprintf("%.2f", $package['price'] * $discount);
            }
        }
        if ($data['no_free_time']) {
            $data['select_time'] = $data['no_free_time'][count($data['no_free_time']) - 1];
        } else {
            $data['select_time'] = '';
        }
        $this->success('查询成功', $data);
    }


    public function add()
    {
        $fangjian_id = input('fangjian_id');
        $fuwu = input()['selectedDate'][0]['date'];
        $fuwu_sc = input('fuwu_sc');
        $user_id = input('user_id');
        $package_id = input('package_id');
        $type = input('type');
        $is_predetermine_time = input('is_predetermine_time');
        if (empty($fangjian_id)) {
            $this->error('房间id不能为空');
        }
        if (empty($fuwu)) {
            $this->error('服务时间不能为空');
        }
        if (empty($fuwu_sc)) {
            $this->error('服务时长不能为空');
        }
        if (empty($user_id)) {
            $this->error('请先登录');
        }
        $predetermine_time = floatval(Config::get('site.predetermine_time')) ? floatval(Config::get('site.predetermine_time')) : 0;
        if (strtotime($fuwu) < (time() + $predetermine_time * 3600) && $predetermine_time > 0 && $is_predetermine_time == true) {
            $this->error('只可提前' . $predetermine_time . '个小时预约');
        }
        if (empty($farr = Fangjian::get($fangjian_id))) {
            $this->error('房间不存在');
        }
        if ($farr->is_dasao == 1 && Config::get('site.dasao_order') == 1) {
            $this->error('打扫中不能下单');
        }
        $k_time = strtotime($fuwu);
        if ($fuwu_sc < $farr['booking_time']) {
            $this->error($farr['booking_time'] . '小时起订');
        }
        //$order = Db::name('order')->field('id,fuwu,fuwu_sc')->where([

        $times = strtotime(date('Y-m-d 00:00:00')) - 86400 * 2;
        $order = Db::name('order')->field('id,fuwu,fuwu_sc')->where([
            'fangjian_id' => $fangjian_id,
            'status' => ['in', ['1', '2', '5']]
        ])->where("UNIX_TIMESTAMP(fuwu) > " . $times)->fetchSql(false)->select();
        $astart = $k_time;//第1个开始
        $aend = $k_time + $fuwu_sc * 60 * 60;//第1个结束
        foreach ($order as &$v) {
            $q_time = strtotime($v['fuwu']);
            $f_time = $q_time + $v['fuwu_sc'] * 60 * 60;
            $bstart = $q_time;//第2个开始
            $bend = $f_time;//第2个结束
            $isIntersection = false;
            if ($bstart - $astart > 0) {
                if ($bstart - $aend <= 0) {
                    $isIntersection = true;
                }
            } else {
                if ($bend - $astart > 0) {
                    $isIntersection = true;
                }
            }
            if ($isIntersection == true) {
                $this->error('房间该时间段已有人预订');
            }
        }

        $look_time = Db::name('look_time')->where([
            'fangjian_id' => $fangjian_id,
        ])->where("UNIX_TIMESTAMP(start_time) > " . time())->select();
        if ($look_time) {
            foreach ($look_time as &$v) {
                $q_time = strtotime($v['start_time']);
                $f_time = $q_time + $v['end_time'] * 60;
                $bstart = $q_time;//第2个开始
                $bend = $f_time;//第2个结束
                $isIntersection = false;
                if ($bstart - $astart > 0) {
                    if ($bstart - $aend <= 0) {
                        $isIntersection = true;
                    }
                } else {
                    if ($bend - $astart > 0) {
                        $isIntersection = true;
                    }
                }
                if ($isIntersection == true) {
                    $this->error('房间该时间段已有人预订');
                }
            }
        }

        $fangjian = Fangjian::get($fangjian_id);
        $org_price = $fuwu_sc * $fangjian['price'];
        $package_vip_price = 0;
        $discount = UserCategoryRmb::getMemberLevel($user_id, $fangjian->category_id);
        if ($type == 0) {
            $fangjian['price'] = sprintf("%.2f", $fangjian['price'] * $discount);
            $price = $fuwu_sc * $fangjian['price'];
            $is_package = 0;
        } else {
            $price = Db::name('fangjian_package')->where(['fj_id' => $fangjian_id, 'id' => $package_id])->value('price');
            if (!$price) {
                $this->error('套餐不存在');
            }
            $org_price = $price;
            $is_package = 1;
            if ($fangjian['package_vip_price'] == 1) {
                if ($discount < 1) {
                    $package_vip_price = 1;
                }
                $price = sprintf("%.2f", $price * $discount);
            }
        }
        $data = [
            'fangjian_id' => $fangjian_id,
            'price' => $price,
            'org_price' => $org_price,
            'fuwu' => $fuwu,
            'fuwu_sc' => $fuwu_sc,
            'user_id' => $user_id,
            'number' => $this->auth->id . date("YmdHis") . mt_rand(100000, 999999),
            'title' => $farr['name'],
            'package_vip_price' => $package_vip_price,
            'is_package' => $is_package,
            //            'zong_price' => $zong_price,
        ];

        $bool = Order::create($data);

        if ($bool) {
            $this->success('下单成功', $bool->id);
        }
        $this->error('下单失败');
    }

    /**
     * 温馨提示
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     *
     */
    public function getTishi()
    {
        $this->success('查询成功', Config::get('site.tishi'));
    }

    /**
     * 我的订单
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $user_id 用户id
     * @param string $page 页
     * @param string $limit 条数
     * @param string $status 状态:0=未支付,1=待消费,2=消费中,3=已完成,4=已取消,5=全部
     */
    public function getOrder()
    {
        $user_id = input('user_id');
        $page = input('page', 1);
        $limit = input('limit', 10);
        $status = input('status');

        if ($status) {
            $where['a.status'] = $status;
        }
        if ($status == 0) {
            $where['a.status'] = '0';
        }
        if ($status == 4) {
            $where['a.status'] = ['in', '4,6'];
        }
        if ($status == 10) {
            unset($where['a.status']);
            $where['a.status'] = ['<>', "5"];
        }

        $where['a.user_id'] = $user_id;
        $where['a.x_status'] = ['in', "0,2"];

        $list = Db::name('order')
            ->alias('a')
            ->join('ims_ymq_changdi_fangjian b ', 'b.id= a.fangjian_id')
            ->join('ims_ymq_changdi_category c ', 'c.id= b.category_id')
            ->field('a.*,
            b.name as fj_name,
            b.id as fangjian_id,
            b.duration,
            b.image as fj_image,
            c.name as md_name,
            c.id as category_id,b.price as prices')
            ->where($where)
            //            ->where('a.status','<>',"5")
            ->order('a.id desc')
            ->paginate($limit, false, [
                'page' => $page,
            ]);
        $list = $list->toArray();

        foreach ($list['data'] as &$v) {
            $discount = UserCategoryRmb::getMemberLevel($user_id, $v['category_id']);
            $v['prices'] = sprintf("%.2f", $v['prices'] * $discount);

            $v['fj_image'] = cdnurl($v['fj_image'], true);

            $v['pinglun'] = Pinglun::where(['order_id' => $v['id']])->count();
            $v['taocan'] = Config::get('site.taocan');
            $v['time'] = strtotime($v['fuwu']);

            $v['uurl'] = 'http://' . $_SERVER['HTTP_HOST'];

            //  $v['uurl'] = cdnurl;

            $shichuang = $v['time'] + $v['fuwu_sc'] * 60 * 60;
            $v['j_time'] = date('Y/m/d H:i:s', $shichuang);

            if ($v['duration'] == 30) {
                $v['durationTime'] = ['30', '60', '90'];
            } else {
                $v['durationTime'] = ['15', '30', '45', '60', '75'];
            }
        }
        $list['kaimen'] = Config::get('site.status');
        $list['order_tpl'] = Config::get('site.template_id');
        $this->success('查询成功', $list);
    }

    public function checkPassword()
    {
        $user_id = input('user_id');
        $order_id = input('order_id');

        $where['user_id'] = $user_id;
        $where['id'] = $order_id;
        $where['status'] = '1';
        $order = Db::name('order')->where($where)->field('fangjian_id,fuwu,fuwu_sc')->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        $k_time = time();
        $fuwu_sc = $order['fuwu_sc'];
        $fangjian_id = $order['fangjian_id'];
        $times = strtotime(date('Y-m-d 00:00:00')) - 86400 * 2;

        $order = Db::name('order')->field('id,fuwu,fuwu_sc')->where([
            'fangjian_id' => $fangjian_id,
            'status' => ['in', ['1', '2', '5']],
            'id' => ['<>', $order_id]
        ])->where("UNIX_TIMESTAMP(fuwu) > " . $times)->select();
        $astart = $k_time;//第1个开始
        $aend = $k_time + $fuwu_sc * 60 * 60;//第1个结束
        foreach ($order as &$v) {
            $q_time = strtotime($v['fuwu']);
            $f_time = $q_time + $v['fuwu_sc'] * 60 * 60;
            $bstart = $q_time;//第2个开始
            $bend = $f_time;//第2个结束
            $isIntersection = false;
            if ($bstart - $astart > 0) {
                if ($bstart - $aend <= 0) {
                    $isIntersection = true;
                }
            } else {
                if ($bend - $astart > 0) {
                    $isIntersection = true;
                }
            }
            if ($isIntersection == true) {
                $this->error('房间该时间段已有人预订');
            }
        }

        $look_time = Db::name('look_time')->where([
            'fangjian_id' => $fangjian_id,
        ])->where("UNIX_TIMESTAMP(start_time) > " . $times)->select();
        if ($look_time) {
            foreach ($look_time as &$v) {
                $q_time = strtotime($v['start_time']);
                $f_time = $q_time + $v['end_time'] * 60;
                $bstart = $q_time;//第2个开始
                $bend = $f_time;//第2个结束
                $isIntersection = false;
                if ($bstart - $astart > 0) {
                    if ($bstart - $aend <= 0) {
                        $isIntersection = true;
                    }
                } else {
                    if ($bend - $astart > 0) {
                        $isIntersection = true;
                    }
                }
                if ($isIntersection == true) {
                    $this->error('房间该时间段已有人预订');
                }
            }
        }
        $res = Db::name('order')->where($where)->update([
            'fuwu' => date('Y-m-d H:i', $k_time)
        ]);
        if (!$res) {
            $this->error('房间不存在');
        }
        $this->success('查询成功');
    }

    /**
     * 获取开锁密码
     */
    public function getLookPassword()
    {
        $user_id = input('user_id');
        $order_id = input('order_id');
        $where['a.user_id'] = $user_id;
        $where['a.id'] = $order_id;
        $where['a.status'] = ['in', '1,2'];
        $detail = Db::name('order')
            ->alias('a')
            ->field("b.room_lock_id,a.fuwu_sc,a.fuwu,a.status,b.duration,b.category_id")
            ->join('ims_ymq_changdi_fangjian b ', 'b.id= a.fangjian_id')
            ->where($where)
            ->find();

        if (!$detail) {
            $this->error('房间不存在');
        }
        $shichuang = strtotime($detail['fuwu']) + $detail['fuwu_sc'] * 60 * 60;
        if (time() > $shichuang) {
            $hall_lock_id = '已过消费时间';
            $room_lock_id = '已过消费时间';
        } else {
            $ttlock = new ttlock();
            $category_hall_lock_id = Db::name('category')->where('id', $detail['category_id'])->value('hall_lock_id');
            if ($category_hall_lock_id) {
                $hall_lock = $ttlock->getPassword($category_hall_lock_id, "hall_" . $order_id);
                if ($hall_lock) {
                    $hall_lock_id = $hall_lock;
                } else {
                    $hall_lock_id = '密码获取失败';
                }
            } else {
                $hall_lock_id = '-';
            }

            if ($detail['room_lock_id']) {
                $room_lock = $ttlock->getPassword($detail['room_lock_id'], "room_" . $order_id);
                if ($room_lock) {
                    $room_lock_id = $room_lock;
                } else {
                    $room_lock_id = '密码获取失败';
                }
            } else {
                $room_lock_id = '-';
            }
        }
        $show_room_lock = false;
        if ($detail['status'] == 2) {
            $show_room_lock = true;
        }


        $this->success('查询成功', [

            'show_room_lock' => $show_room_lock,
            'hall_lock_id' => $hall_lock_id,
            'room_lock_id' => $room_lock_id
        ]);

    }

    /**
     * 取消订单
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $user_id 用户id
     * @param string $order_id 条数
     */
    public function quxiao()
    {
        $user_id = input('user_id');
        $order_id = input('order_id');
        if (empty($user_id)) {
            $this->success('用户id不能为空');
        }
        if (empty($order_id)) {
            $this->success('订单id不能为空');
        }

        $bool = Order::where(['user_id' => $user_id, 'id' => $order_id, 'status' => 1])->update(['status' => 4]);

        $wxModel = new \addons\epay\controller\Wxtuikuan();
        $wxModel->tuikuan($order_id);
        if ($bool) {
            $this->success('取消成功');
        }

        $this->success('取消失败');

    }

    /**
     * 加盟
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $user_id 用户id
     * @param string $username 姓名
     * @param string $card 身份证
     * @param string $phone 手机号
     * @param string $city 城市
     * @param string $content 建议
     */
    public function jiameng()
    {
        $user_id = input('user_id');
        $username = input('username');
        $card = input('card');
        $phone = input('phone');
        $city = input('city');
        $content = input('content');


        if (empty($user_id)) {
            $this->success('用户id不能为空');
        }
        if (empty($username)) {
            $this->success('姓名不能为空');
        }
        // if (empty($card)) {
        //     $this->success('身份证号不能为空');
        // }
        if (empty($phone)) {
            $this->success('手机号不能为空');
        }
        if (empty($city)) {
            $this->success('城市不能为空');
        }

        $data = [
            'user_id' => $user_id,
            'username' => $username,
            // 'card' => $card,
            'phone' => $phone,
            'city' => $city,
            'content' => $content,
        ];

        $bool = Jiameng::create($data);

        if ($bool) {
            $this->success('加盟成功,等待审核');
        }

        $this->success('加盟失败');

    }


    /**
     * 认证
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $user_id 用户id
     * @param string $name 姓名
     * @param string $card 身份证号
     * @param string $z_image 身份证照片
     * @param string $f_image 身份证照片
     */
    public function renzheng()
    {
        $user_id = input('user_id');
        $name = input('name');
        $card = input('card');
        $z_image = input('z_image');
        $f_image = input('f_image');


        if (empty($user_id)) {
            $this->success('用户id不能为空');
        }
        if (empty($name)) {
            $this->success('姓名不能为空');
        }
        if (empty($z_image)) {
            $this->success('身份证号不能为空');
        }
        if (empty($f_image)) {
            $this->success('手机号不能为空');
        }

        $data = [
            'user_id' => $user_id,
            'name' => $name,
            'card' => $card,
            'z_image' => $z_image,
            'f_image' => $f_image,
        ];

        $bool = Renzheng::create($data);

        if ($bool) {
            $this->success('认证成功,等待审核');
        }

        $this->success('认证失败');

    }

    /**
     * 发表评论
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $user_id 用户id
     * @param string $xing 星
     * @param string $content 内容
     * @param string $images 图片
     * @param string $category_id 商家id
     * @param string $fangjian_id 订单id
     */
    public function addpinglun()
    {
        $user_id = input('user_id');
        $xing = input('xing');
        $content = input('content');
        $images = input('images');
        $category_id = input('category_id');
        $order_id = input('order_id');


        if (empty($user_id)) {
            $this->success('用户id不能为空');
        }
        if (empty($xing)) {
            $this->success('');
        }
        if (empty($content)) {
            $this->success('内容不能为空');
        }
        if (empty($category_id)) {
            $this->success('商家id不能为空');
        }

        $data = [
            'user_id' => $user_id,
            'xing' => $xing,
            'content' => $content,
            'images' => $images,
            'category_id' => $category_id,
            'order_id' => $order_id,
        ];

        $bool = Pinglun::create($data);

        if ($bool) {
            $this->success('评论成功');
        }

        $this->success('评论失败');

    }


    /**
     * 公告管理
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGonggao()
    {
        $data = Gonggao::where('status', 1)->select();

        $this->success('查询成功', $data);
    }

    /**
     * 订单详情
     * @param string $id 订单id
     */
    public function orderxiangqing()
    {
        $id = input('id');

        $data = Order::get($id);

        $fangjian = Fangjian::where('id', $data['fangjian_id'])->find();
        $data['mendian'] = Category::get($fangjian->category_id);
        $data['fangjian'] = $fangjian;
        // $data['uurl'] = 'http://' . $_SERVER['HTTP_HOST'];
        $data['uurl'] = cdnurl('', true);
        $data['order_tpl'] = Config::get('site.template_id');
        $data['discount'] = UserCategoryRmb::getMemberLevel($data['user_id'], $fangjian->category_id) * 10;
        $this->success('查询成功', $data);
    }

    /**
     * 续费
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $fangjian_id 房间id
     * @param string $order_id 订单id
     * @param string $fuwu_sc 服务时长套餐
     * @param string $user_id 用户id
     */
    public function orderXufei()
    {
        $order_id = input('order_id');
        $fuwu_sc = input('fuwu_sc');
        $user_id = input('user_id');
        if (empty($fuwu_sc)) {
            $this->success('服务时长不能为空');
        }
        if (empty($user_id)) {
            $this->success('用户id不能为空');
        }
        $order = Db::name('order')->where([
            'user_id' => $user_id,
            'status' => ['in', ['1', '2', '5']],
            'id' => $order_id
        ])->find();
        if (!$order) {
            $this->success('续费订单不存在');
        }

        $fangjian_id = $order['fangjian_id'];
        if (empty($farr = Fangjian::get($fangjian_id))) {
            $this->success('房间不存在');
        }
        $fuwu = date('Y-m-d H:i:s', strtotime($order['fuwu']) + $order['fuwu_sc'] * 60 * 60);
        $k_time = strtotime($fuwu);
        if (time() > ($k_time - 10 * 60)) {
            $this->success('续费订单只能提前十分钟续费');
        }

        $order = Db::name('order')->field('id,fuwu,fuwu_sc')->where([
            'fangjian_id' => $fangjian_id,
            'status' => ['in', ['1', '2', '5']]
        ])->where("UNIX_TIMESTAMP(fuwu) > " . time())->select();

        $astart = $k_time;//第1个开始
        $aend = $k_time + $fuwu_sc * 60 * 60;//第1个结束
        foreach ($order as &$v) {
            $q_time = strtotime($v['fuwu']);
            $f_time = $q_time + $v['fuwu_sc'] * 60 * 60;
            $bstart = $q_time;//第2个开始
            $bend = $f_time;//第2个结束
            $isIntersection = false;
            if ($bstart - $astart > 0) {
                if ($bstart - $aend <= 0) {
                    $isIntersection = true;
                }
            } else {
                if ($bend - $astart > 0) {
                    $isIntersection = true;
                }
            }
            if ($isIntersection == true) {
                $this->error('房间该时间段已有人预订');
            }
        }
        $fangjian = Fangjian::get($fangjian_id);

        $discount = UserCategoryRmb::getMemberLevel($user_id, $fangjian->category_id);
        $fangjian['price'] = $fangjian['price'] * $discount;
        $price = $fuwu_sc * $fangjian['price'];
        $data = [
            'fuwu' => $fuwu,
            'fangjian_id' => $fangjian_id,
            'price' => $price,
            'fuwu_sc' => $fuwu_sc,
            'user_id' => $user_id,
            'number' => $this->auth->id . date("YmdHis") . mt_rand(100000, 999999),
            'title' => $farr['name'],
            'x_status' => 1,
            'x_id' => $order_id
        ];
        $bool = Order::create($data);
        if ($bool) {
            $this->success('下单成功', $bool->id);
        }
        $this->success('下单失败');
    }

    /**
     * 续费
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $fangjian_id 房间id
     * @param string $order_id 订单id
     * @param string $fuwu_sc 服务时长套餐
     * @param string $user_id 用户id
     */
    public function orderXufeiTime()
    {
        $order_id = input('order_id');
        $fuwu_sc = input('fuwu_sc');
        $user_id = input('user_id');

        if (empty($fuwu_sc)) {
            $this->success('服务时长不能为空');
        }
        if (empty($user_id)) {
            $this->success('用户id不能为空');
        }
        $order = Db::name('order')->where([
            'user_id' => $user_id,
            'status' => ['in', ['1', '2', '5']],
            'id' => $order_id
        ])->find();
        if (!$order) {
            $this->success('续费订单不存在');
        }

        $fangjian_id = $order['fangjian_id'];
        if (empty($farr = Fangjian::get($fangjian_id))) {
            $this->success('房间不存在');
        }
        $fuwu = date('Y-m-d H:i:s', strtotime($order['fuwu']) + $order['fuwu_sc'] * 60 * 60);
        $k_time = strtotime($fuwu);
        if (time() > ($k_time - 10 * 60)) {
            $this->success('续费订单只能提前十分钟续费');
        }

        $order = Db::name('order')->field('id,fuwu,fuwu_sc')->where([
            'fangjian_id' => $fangjian_id,
            'status' => ['in', ['1', '2', '5']]
        ])->where("UNIX_TIMESTAMP(fuwu) > " . time())->select();
        $astart = $k_time;//第1个开始
        $aend = $k_time + $fuwu_sc * 60 * 60;//第1个结束
        foreach ($order as &$v) {
            $q_time = strtotime($v['fuwu']);
            $f_time = $q_time + $v['fuwu_sc'] * 60 * 60;
            $bstart = $q_time;//第2个开始
            $bend = $f_time;//第2个结束
            $isIntersection = false;
            if ($bstart - $astart > 0) {
                if ($bstart - $aend <= 0) {
                    $isIntersection = true;
                }
            } else {
                if ($bend - $astart > 0) {
                    $isIntersection = true;
                }
            }
            if ($isIntersection == true) {
                $this->error('房间该时间段已有人预订');
            }
        }

        $look_time = Db::name('look_time')->where([
            'fangjian_id' => $fangjian_id,
        ])->where("UNIX_TIMESTAMP(start_time) > " . time())->select();
        if ($look_time) {
            foreach ($look_time as &$v) {
                $q_time = strtotime($v['start_time']);
                $f_time = $q_time + $v['end_time'] * 60;
                $bstart = $q_time;//第2个开始
                $bend = $f_time;//第2个结束
                $isIntersection = false;
                if ($bstart - $astart > 0) {
                    if ($bstart - $aend <= 0) {
                        $isIntersection = true;
                    }
                } else {
                    if ($bend - $astart > 0) {
                        $isIntersection = true;
                    }
                }
                if ($isIntersection == true) {
                    $this->error('房间该时间段已有人预订');
                }
            }
        }

        $this->success('正确', ['data' => '1']);
    }

    /**
     * 定时完成订单
     * @return void
     */
    public function dingshiwancheng()
    {
        // 已经有 不需要调用
        die;
        $list = Order::where(['status' => 2])->select();

        foreach ($list as &$v) {
            $v['fuwu'] = strtotime($v['fuwu']);
            $jtime = $v['fuwu'] + $v['fuwu_sc'] * 60 * 60;
            if (time() > $jtime) {
                Order::where('id', $v['id'])->update(['status' => 3]);
                echo '执行订单' . $v['id'] . '成功-';
            }
        }
    }

    /**
     * 定时消费订单
     * @return void
     */
    public function dingshixiaofei()
    {
        // 已经有 不需要调用
        die;
        $list = Order::where(['status' => 1])->select();

        foreach ($list as &$v) {
            $v['fuwu'] = strtotime($v['fuwu']);
            if (time() > $v['fuwu']) {
                Order::where('id', $v['id'])->update(['status' => 2]);
                echo '执行订单' . $v['id'] . '成功-';
            }
        }

    }

    /**
     * 定时删除订单
     * @return void
     */
    public function dingshishanchu()
    {
        $list = Order::where(['status' => 0])->select();

        foreach ($list as &$v) {
            $v['fuwu'] = strtotime($v['fuwu']);
            if (time() > $v['fuwu']) {
                Order::where('id', $v['id'])->delete();
                echo '执行订单' . $v['id'] . '成功-';
            }
        }

    }


    /**
     * 订单提醒
     *
     * @ApiSummary  (描述信息)
     * @ApiMethod   (POST)
     * @param string $user_id 用户id
     */
    public function getDingdanStatus()
    {
        //        $user_id = input('user_id');
        $list = Order::where(['status' => 2, 'tixing_status' => 0])->select();
        if (empty($list)) {
            $this->success('暂无提示订单');
        }
        $order['id'] = 0;
        foreach ($list as &$v) {
            $v['time'] = strtotime($v['fuwu']);
            $shichuang = $v['time'] + $v['fuwu_sc'] * 60 * 60 - 900;

            if (time() >= $shichuang) {
                $order = $v;
                $user = \app\admin\model\User::where('id', $v['user_id'])->find();
                $user['number'] = $v['number'];

                $this->tuisong($user);
                Order::where(['id' => $v['id']])->update(['tixing_status' => 1]);

                if ($user['mobile']) {

                    $sms = new smsIndex();
                    $sms->send($v['mobile']);
                }


            }
        }


        $this->success('提示信息', $order['id']);

    }


    public function phone()
    {
        $sms = new smsIndex();
        $bool = $sms->send(18844901140);
        print_r($bool);
        die;
    }


    function Http($url, $data, $type = "http")
    {
        $curl = curl_init();
        if ($type == "json") {
            $headers = array("Content-type: application/json;charset=UTF-8");
            $data = json_encode($data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;

    }

    /**
     * token
     * @return void
     */
    public function token()
    {
        $user_id = input('user_id');
        if (empty($user_id)) {
            $this->error('id 不存在');
        }
        $user = \app\admin\model\User::where('id', $user_id)->find();
        if (empty($user)) {
            $this->error('用户不存在');
        }

        $bool = \app\admin\model\User::where('id', $user_id)->update(['access_token' => $this->getaccesstoken()]);
        if ($bool) {
            $this->success('获取成功');
        }
        $this->error('获取失败');
    }

    function getaccesstoken()
    {

        $appid = Config::get('site.appid');
        $appsecret = Config::get('site.appsecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $html = file_get_contents($url);
        $output = json_decode($html, true);
        //        print_r($output);die;
        $access_token = $output['access_token'];

        return $access_token;
    }

    /**
     * 发送消息
     * @return void
     */
    public function tuisong($arr)
    {
        $data = [
            "touser" => $arr['openid'],
            "template_id" => Config::get('site.template_id'),
            "data" => [
                "character_string2" => [
                    "value" => $arr['number'],
                ],
                "thing4" => [
                    "value" => Config::get('site.content'),

                ]
            ]
        ];

        $ast = $this->getaccesstoken(); //ACCESS_TOKEN

        //        print_r($ast);die;
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $ast;
        $client = new Client();
        $data = json_encode($data);
        $r = $client->request("POST", $url, [
            'body' => $data
        ]);

    }

    function https_request($url, $data = null)
    {
        $curl = curl_init();
        $data = json_encode($data);

        $header = [
            "Content-Type: application/json;"
        ];

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function upPhone()
    {
        $user_id = input('user_id');
        $phone = input('phone');

        if (empty($phone)) {
            $this->error('手机号不能为空');
        }
        if (empty($user_id)) {
            $this->error('用户id不能为空');
        }

        $bool = \app\admin\model\User::where('id', $user_id)->update(['mobile' => $phone]);
        if ($bool) {
            $this->success('手机号获取成功');
        } else {
            $this->error('手机号获取失败');
        }
    }

    public function qrcode(Wechat $wechat)
    {
        $scene = input('scene');
        $page = input('page');

        echo $wechat->qrcode($scene, $page);
    }

    /**核销订单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function write_off()
    {
        $id = input('id');
        $userId = input('user_id');

        $order = Order::findOrFail($id);
        $user = \app\common\model\User::findOrFail($userId);

        if (!$user->is_clerk) {
            $this->error('您无权核销');
        }

        $order->is_write_off = 1;
        $order->status = '2';
        $order->save();

        $this->success($order);
    }

    // 订单消费中
    public function cronOrderConsumption()
    {
        $list = Db::name('order')
            ->alias('a')
            ->field("a.id,b.closing_command")
            ->join('ims_ymq_changdi_fangjian b ', 'b.id= a.fangjian_id')
            ->where("a.status = '1' and UNIX_TIMESTAMP(a.fuwu) < UNIX_TIMESTAMP(NOW())")
            ->select();
        dump($list);
        die;
        $log_path = ROOT_PATH . "public/closing_command_stock.html";
        foreach ($list as $item) {
            file_put_contents($log_path, '<meta charset="UTF-8"><pre>----发送命令：' . date('Y-m-d H:i:s') . '----' . PHP_EOL, FILE_APPEND);
            file_put_contents($log_path, '订单ID：' . $item['id'] . '----' . PHP_EOL, FILE_APPEND);
            file_put_contents($log_path, '订单状态：待消费' . PHP_EOL, FILE_APPEND);
            if ($item['closing_command']) {
                $res = $this->sendTcp($item['closing_command'], $log_path);
            } else {
                file_put_contents($log_path, 'TCP无需发送' . PHP_EOL, FILE_APPEND);
                $res = true;
            }
            if ($res === false) {
                file_put_contents($log_path, 'TCP发送失败' . PHP_EOL, FILE_APPEND);
            } else {
                $rs = Order::where('id', $item['id'])->update(['is_write_off' => 1, 'status' => 2]);
                if ($rs) {
                    file_put_contents($log_path, '订单状态：消费中' . PHP_EOL, FILE_APPEND);
                } else {
                    file_put_contents($log_path, '订单状态：修改失败' . PHP_EOL, FILE_APPEND);
                }
            }
            file_put_contents($log_path, "---end---" . PHP_EOL . PHP_EOL . PHP_EOL, FILE_APPEND);
        }
    }

    // 订单消费中
    public function cronOrderComplete()
    {
        $list = Db::name('order')
            ->alias('a')
            ->field("a.id,b.opening_command,a.fuwu,a.fuwu_sc")
            ->join('ims_ymq_changdi_fangjian b ', 'b.id= a.fangjian_id', "left")
            ->where(['a.status' => '2'])
            ->select();
        $log_path = ROOT_PATH . "public/opening_command_stock.html";
        foreach ($list as $item) {
            $item['fuwu'] = strtotime($item['fuwu']);
            $jtime = $item['fuwu'] + $item['fuwu_sc'] * 60 * 60;
            if (time() > $jtime) {
                file_put_contents($log_path, '<meta charset="UTF-8"><pre>----发送命令：' . date('Y-m-d H:i:s') . '----' . PHP_EOL, FILE_APPEND);
                file_put_contents($log_path, '订单ID：' . $item['id'] . '----' . PHP_EOL, FILE_APPEND);
                file_put_contents($log_path, '订单状态：消费中' . PHP_EOL, FILE_APPEND);
                if ($item['opening_command']) {
                    $res = $this->sendTcp($item['opening_command'], $log_path);
                } else {
                    file_put_contents($log_path, 'TCP无需发送' . PHP_EOL, FILE_APPEND);
                    $res = true;
                }
                if ($res === false) {
                    file_put_contents($log_path, 'TCP发送失败' . PHP_EOL, FILE_APPEND);
                } else {
                    $rs = Order::where('id', $item['id'])->update(['status' => 3]);
                    if ($rs) {
                        file_put_contents($log_path, '订单状态：完成' . PHP_EOL, FILE_APPEND);
                    } else {
                        file_put_contents($log_path, '订单状态：修改失败' . PHP_EOL, FILE_APPEND);
                    }
                }
                file_put_contents($log_path, "---end---" . PHP_EOL . PHP_EOL . PHP_EOL, FILE_APPEND);
            }
        }
    }


    // 发送命令
    public function sendTcp($sendStr, $log_path)
    {
        die;
        error_reporting(E_ALL);
        $service_port = Config::get('site.tcp_port');; //这里是端口号
        $address = Config::get('site.tcp_ip');;//这里输入服务器端IP地址

        file_put_contents($log_path, "地址：{$address}:{$service_port}" . PHP_EOL, FILE_APPEND);
        file_put_contents($log_path, "发送内容：{$sendStr}" . PHP_EOL, FILE_APPEND);

        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket < 0) {
            file_put_contents($log_path, "socket创建失败原因: " . socket_strerror($socket) . PHP_EOL, FILE_APPEND);
            return false;
        } else {
            file_put_contents($log_path, "socket创建成功" . PHP_EOL, FILE_APPEND);
        }
        $result = socket_connect($socket, $address, $service_port);
        if ($result < 0) {
            file_put_contents($log_path, "SOCKET连接失败原因: " . socket_strerror($result) . PHP_EOL, FILE_APPEND);
            return false;
        } else {
            file_put_contents($log_path, "SOCKET连接成功" . PHP_EOL, FILE_APPEND);
        }
        $sendStrArray = str_split(str_replace(' ', '', $sendStr), 2);  // 将16进制数据转换成两个一组的数组
        for ($j = 0; $j < count($sendStrArray); $j++) {
            socket_write($socket, chr(hexdec($sendStrArray[$j])));  // 逐组数据发送
        }
        $receiveStr = "";
        $receiveStr = socket_read($socket, 1024, PHP_BINARY_READ);  // 采用2进制方式接收数据
        $receiveStrHex = bin2hex($receiveStr);  // 将2进制数据转换成16进制
        $data = implode(" ", str_split(str_replace(' ', '', $receiveStrHex), 2));
        socket_close($socket);  // 关闭Socket
        file_put_contents($log_path, "返回内容: {$data}" . PHP_EOL, FILE_APPEND);
        return $data;
    }

    // 开锁回调
    public function lookCallback()
    {
        $ttlock = new ttlock();
        $ttlock->lockRecord('7056139');


        file_put_contents(APP_PATH . "../public/lookCallback.text",
            "===============" . date('Y-m-d H:i:s') . "\n\r" .
            "input \n\r" .
            var_export(input(), true) . "\n\r" .
            "file_get_contents \n\r" .
            file_get_contents("php://input") . "\n\r"
            , FILE_APPEND);
    }

    // 图片上传处理
    public function picture()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        //校验器，判断图片格式是否正确
        if (true !== $this->validate(['image' => $file], ['image' => 'require|image'])) {
            $this->error('请选择图像文件');
        } else {
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                // 成功上传后 获取上传信息
                //存入相对路径/upload/日期/文件名
                $data = DS . 'uploads' . DS . $info->getSaveName();
                $this->success('上传成功', $data);
            } else {
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        }
    }

    // 订单消费中
    public function sendSettlementMoney()
    {
        set_time_limit(0);
        $list = Db::name('order')->where(['status' => '3', 'is_send_settlement_money' => 0])->limit(10)->order('id asc')->select();
        $order_commission_type = Config::get('site.order_commission_type'); //
        $profit_sharing_valid_duration = Config::get('site.profit_sharing_valid_duration'); // 有效分账时长
        $order_commission = floatval(Config::get('site.order_commission'));
        $order_commission = $order_commission ? $order_commission : 0;
        $order_commission_type_text = '';
        if ($order_commission_type == 1) {
            $order_commission_type_text = "服务费固定金额：{$order_commission}";
        } elseif ($order_commission_type == 0) {
            $order_commission_type_text = "服务费百分比：{$order_commission}%";
        }

        // 是否开启自动分账
        $is_auto_profit_sharing = config('site.is_auto_profit_sharing');

        if ($list) {
            foreach ($list as $item) {
                // 商家代下单无需结算
                if ($item['x_status'] == 2) {
                    Db::name('order')->where(['id' => $item['id']])->update([
                        'is_send_settlement_money' => 2
                    ]);
                    continue;
                }
                // 只结算微信支付
                if ($item['pay_type'] != 1) {
                    Db::name('order')->where(['id' => $item['id']])->update([
                        'is_send_settlement_money' => 2
                    ]);
                    continue;
                }
                // 结算服务费
                $settlement_money = $item['settlement_money'];
                $send_settlement_money = $settlement_money;
                if ($order_commission_type == 1) {
                    $send_settlement_money = $settlement_money - $order_commission;
                } elseif ($order_commission_type == 0) {
                    $send_settlement_money = round($settlement_money - ($settlement_money * $order_commission / 100), 2);
                }
                Db::startTrans();
                try {
                    if ($is_auto_profit_sharing && $item['profit_sharing_status'] == 0) {
                        \app\admin\model\Order::profitSharing($item['id']);
                    } else if (time() - $item['createtime'] >= $profit_sharing_valid_duration * 86400) {
                        $shop_id = Db::name('fangjian')->where("id", $item['fangjian_id'])->value('category_id');
                        Db::name('order')->where(['id' => $item['id']])->update([
                            'is_send_settlement_money' => 1,
                            'settlement_amount' => $send_settlement_money,
                        ]);
                        if ($shop_id && $send_settlement_money) {
                            $rs1 = \app\admin\model\CategoryMoneyLog::_do($shop_id, $send_settlement_money, 3, "订单结算:订单编号：{$item['number']}，订单结算金额：{$item['settlement_money']}，$order_commission_type_text");
                        }
                    }

                    Db::commit();
                } catch (DbException $e) {
                    Db::rollback();
                }
            }
        }
    }

}
